package io.renren.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.renren.bean.ExamQuestionInfo;
import io.renren.bean.ExamResult;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.dao.ExamDao;
import io.renren.entity.*;
import io.renren.util.ExamUtil;
import io.renren.util.Query;
import io.renren.util.StringUtils;
import io.renren.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 * 试卷
 * @author 霍礼康
 */
@Service("examService")
public class ExamServiceImpl extends ServiceImpl<ExamDao, ExamEntity> implements ExamService {
    @Autowired
    private ExamTemplateService examTemplateService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private ExamDatailsService examDatailsService;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private StuSubService stuSubService;
    @Autowired
    private QuestionErrorService questionErrorService;
    @Autowired
    private ExamService examService;

    /***
     * 获取考试信息  主要获取剩余时间
     * @param examId 试卷id
     * @return
     */
    @Override
    public Map<String, Object> getPaperMap(Integer examId) {

        return baseMapper.getPaperMap(examId);
    }

    /**
     * 创建试卷
     *
     * @param @param  student 学员
     * @param @param  subjectId 科目id
     * @param @return
     * @return R
     * @author huolikang
     * @date 2018年10月31日
     */
    @Override
    public R createExamPaper(StudentEntity student, Integer subjectId) {

        StuSubEntity subStudent = stuSubService.stuSub(subjectId, student.getUserId());
        if (subStudent == null) {
            return R.fail("暂不能使用该科目");
        }
        //查看是否能创建试卷
        Integer i = examService.checkCreateExam(subjectId, student.getUserId());
        if (i == 1) {
            return R.fail("1.所选科目不存在");
        } else if (i == 2) {
            return R.fail("2.暂无可用于考试的试卷");
        } else if (i == 3) {
            //查找学员未提交试卷id
            Integer unommExamId = examService.findUnommExamId(student.getUserId(), subjectId);
            //获取考试信息 主要获取剩余时间
            Map<String, Object> paperMap = examService.getPaperMap(unommExamId);
            //获取剩余时间
            Integer remainExamSecond = examService.getRemainExamSecond(paperMap);
            return R.fail1("有未提交试卷", unommExamId, remainExamSecond);
        } else if (i == 4) {
            return R.fail("4.超出考试有效次数");
        } else {
            //查看试卷题目是否足够
            Integer j = questionService.checkQuestion(subjectId);
            if (j == 1) {
                return R.fail("单选题不够");
            } else if (j == 2) {
                return R.fail("多选题不够");
            } else if (j == 3) {
                return R.fail("判断题不够");
            } else {
                //创建试卷 并返回id
                Integer examId = examService.createExam(student.getUserId(), subjectId);
                Map<String, Object> map = new HashMap<>();
                map.put("examId", examId);
                return R.ok(map);
            }

        }


    }


    /**
     * 获取考试记录
     *
     * @param @param  studentId 学员id
     * @param @param  subjectId 科目id
     * @param @return
     * @return CommonResult
     * @throws
     * @Description: TODO
     * @author huolikang
     * @date 2018年10月30日
     */
    @Override
    public List<Map<String, Object>> getExamList(Long studentId, Integer subjectId) {
        return baseMapper.getExamList(studentId, subjectId);
    }

    /***
     * 查看是否能创建试卷
     * 0.表示通过；
     * 1.表示选中的科目不存在或者已被删除；
     * 2.表示暂无可用于考试的试卷；
     * 3.表示有未提交的试卷；
     * 4.表示超出考试有效次数；
     * 5.表示考试时间已过期，
     * 6.表示暂未到考试时间
     * @param subjectId 科目id
     * @param studentId 学员id
     * @return
     */
    @Override
    public Integer checkCreateExam(Integer subjectId, Long studentId) {
        //查看所选科目是否存在 1
        Map<String, Object> subjectMap = baseMapper.getSubjectMap(subjectId);
        if (subjectMap == null || subjectMap.size() == 0) {
            return 1;
        }
        // 2.表示暂无可用于考试的试卷；
        Map<String, Object> examPaperMap = baseMapper.getExamPaperMap(subjectId);
        if (examPaperMap == null || examPaperMap.size() == 0) {
            return 2;
        }
        //试卷id
        Integer examPaperId = Integer.parseInt(examPaperMap.get("examPaperId").toString());
        //3.表示有未提交的试卷；
        List<Map<String, Object>> examList = baseMapper.getExamList2(studentId, examPaperId);
        if (examList != null && examList.size() > 0) {
            return 3;
        }
        //获取该科目的考试模块有效次数
        Map<String, Object> getValidCount = baseMapper.getValidCount(subjectId);
        //该科目的有效次数
        Integer validCount = Integer.parseInt(getValidCount.get("validCount").toString());
        if (validCount != 0) {
            //获取该学员在该科目所做考试模块的次数
            Map<String, Object> getExamCount = baseMapper.getExamCount(studentId, subjectId);
            Integer examCount = Integer.parseInt(getExamCount.get("examCount").toString());
            //学员考试次数 >= 科目规定次数 超出考试有效次数
            if (examCount >= validCount) {
                return 4;
            }
        }
        return 0;
    }

    /**
     * 创建试卷 并返回id
     *
     * @param studentId 学员id
     * @param subjectId 科目id
     * @return integer
     */
    @Override
    public Integer createExam(Long studentId, Integer subjectId) {
        EntityWrapper<ExamTemplateEntity> entityEntityWrapper = new EntityWrapper<>();
        entityEntityWrapper.eq("subject_id", subjectId);
        //找出试卷模板
        ExamTemplateEntity examTemplateEntity = examTemplateService.selectOne(entityEntityWrapper);
        StudentEntity student = studentService.selectById(studentId);
        if (examTemplateEntity != null) {
            //创建exam实体
            ExamEntity bean = new ExamEntity();
            //准确率
            bean.setCorrectrate(null);
            //学员id
            bean.setStudentId(studentId);
            //1未开始 2考试中 3已交卷
            bean.setState(1);
            bean.setLastModifyDate(new Date());
            //开始做题时间
            bean.setStartTime(new Timestamp(System.currentTimeMillis()));
            bean.setCreateDate(new Date());
            //结束做题时间
            bean.setEndTime(null);
            //试卷模板id
            bean.setExamTemId(examTemplateEntity.getId());
            //做题总时间
            bean.setTotalTime(null);
            //做题总分
            bean.setTotalScore(null);
            //获取做过的exam数量
            List<Map<String, Object>> sort = baseMapper.getExamSort(studentId, examTemplateEntity.getId());
            Integer sort1 = sort == null ? 0 : sort.size();
            bean.setSort(sort1 + 1);
            insert(bean);
            //插入详情表
            examDatailsService.createExam(studentId, bean.getId(), examTemplateEntity);
            return bean.getId();
        }
        return null;
    }

    /***
     * 获取考试题目
     *
     * @param examId 试卷id
     * @param studentId 学员id
     * @return R
     */
    @Override
    public ExamQuestionInfo getExamQuestionInfo(Integer examId, Long studentId) {
        ExamQuestionInfo examQuestionInfo = new ExamQuestionInfo();
        Map<String, Object> paperMap = baseMapper.getPaperMap(examId);
        if (paperMap != null && paperMap.size() > 0) {
            //当前试卷考试剩余时间
            Integer remainExamSecond = paperMap.get("remainExamSecond") == null ? 0
                    : Double.valueOf(paperMap.get("remainExamSecond").toString()).intValue();
            // 当前试卷总题数
            Integer sumQuestionNumber = paperMap.get("sumQuestionNumber") == null ? 0
                    : Double.valueOf(paperMap.get("sumQuestionNumber").toString()).intValue();
            // 当前试卷已答题数量
            Integer answerNumber = paperMap.get("answerNumber") == null ? 0
                    : Double.valueOf(paperMap.get("answerNumber").toString()).intValue();
            // 1表示未开始，2表示考试中，3表示已交卷
            Integer state = paperMap.get("state") == null ? 0
                    : Double.valueOf(paperMap.get("state").toString()).intValue();
            examQuestionInfo.setAnswerNumber(answerNumber);
            examQuestionInfo.setExamId(examId);
            examQuestionInfo.setRemainExamSecond(remainExamSecond);
            examQuestionInfo.setState(state);
            examQuestionInfo.setSumQuestionNumber(sumQuestionNumber);
            //获取考试题目
            List<Map<String, Object>> questionList = baseMapper.getQuestionList(examId, studentId);
            return ExamUtil.checkExamQuestionInfo(questionList, examQuestionInfo, state);
        }
        return null;
    }

    /**
     * 提交某一道题的答案
     *
     * @param @param student.getUserId() 学员id
     * @param @param examId 考试id
     * @param @param questionId 问题id
     * @param @param sort 序号
     * @param @param remainExamSecond 考试剩下时间（秒）
     * @param @param studentAnswer 学员答案
     * @return R
     * @author huolikang
     * @date 2018年11月1日
     */
    @Override
    public void submitQuestion(Integer examId, Integer questionId, Integer sort, Integer remainExamSecond, String studentAnswer) {
        //找出该试卷exam
        ExamEntity exam = this.selectById(examId);
        if (exam != null && (exam.getState() == 1 || exam.getState() == 2)) {
            //找出该试卷的模板
            ExamTemplateEntity examPaper = examTemplateService.selectById(exam.getExamTemId());
            if (examPaper != null) {
                //使用时间
                exam.setTotalTime(examPaper.getExamMinute() * 60 - remainExamSecond);
            }
            //1.未开始 2.考试中 3.已经交卷
            exam.setState(2);
            exam.setLastModifyDate(new Date());
            updateAllColumnById(exam);
            EntityWrapper<ExamDatailsEntity> entityEntityWrapper = new EntityWrapper<>();
            entityEntityWrapper.eq("exam_id", examId);
            entityEntityWrapper.eq("question_id", questionId);
            entityEntityWrapper.eq("sort", sort);
            //找出试卷详情(题目)
            ExamDatailsEntity examDatails = examDatailsService.selectOne(entityEntityWrapper);
            if (examDatails != null) {
                if (StringUtils.isNotBlank(studentAnswer)) {
                    //学生答案
                    examDatails.setStudentAnswer(studentAnswer);
                    //做题状态（1表示未做题，2表示已答题）
                    examDatails.setState(2);
                    QuestionEntity question = questionService.selectById(questionId);
                    if (question != null) {
                        if (question.getTrueAnswer().equals(studentAnswer)) {
                            //正确
                            examDatails.setIsTrue(true);
                            //1单选 2多选 3判断
                            Integer optionType = question.getOptionType();
                            if (optionType == 1) {
                                examDatails.setScore(examPaper.getRadioScore());
                            } else if (optionType == 2) {
                                examDatails.setScore(examPaper.getCheckScore());
                            } else if (optionType == 3) {
                                examDatails.setScore(examPaper.getJudegScore());
                            }
                        } else {
                            examDatails.setIsTrue(false);
                            examDatails.setScore(0d);
                        }
                    }
                } else {
                    //如果没提交题目答案  依然保存题目，状态还是未完成，分数是0，题目错误
                    examDatails.setStudentAnswer(studentAnswer);
                    examDatails.setState(1);
                    examDatails.setScore(0d);
                    examDatails.setIsTrue(false);
                }
                examDatails.setLastModifyDate(new Date());
                examDatailsService.updateAllColumnById(examDatails);
            }
        }


    }

    /**
     * 学员提交试卷
     *
     * @param examId    考试id
     * @param subjectId 科目id
     * @param studentId 学员
     * @return R
     * @author huolikang
     * @date 2018年11月2日
     */
    @Override
    public ExamResult submitExam(Integer examId, Integer subjectId, Long studentId) {
        // ①：统计信息到考试表；②统计信息到科目学员中间表；③错题入库
        StuSubEntity subStudent = stuSubService.stuSub(subjectId, studentId);
        ExamResult examResult = new ExamResult();
        //更新考试表
        baseMapper.updateExam(examId);
        if (subStudent != null) {
            Integer subId = subStudent.getId();
            //更新学员_科目中间表（更新这学员的最高分，最低分，平均分，剩余考试次数）
            baseMapper.updateSubStudent(examId, subId, studentId);
        }
        String maxScore=subStudent.getMaxScore().toString();
        examResult.setMaxScore(maxScore);
        EntityWrapper<ExamDatailsEntity> entityEntityWrapper = new EntityWrapper<>();
        entityEntityWrapper.eq("exam_id", examId);
        entityEntityWrapper.eq("is_true", false);
        entityEntityWrapper.eq("state", 2);
        List<ExamDatailsEntity> examDatailsList = examDatailsService.selectList(entityEntityWrapper);
        if (examDatailsList != null && examDatailsList.size() > 0) {
            for (int i = 0; i < examDatailsList.size(); i++) {
                //错题入库
                questionErrorService.errorQuestionStorage(studentId, examDatailsList.get(i).getQuestionId());
            }
        }
        //计算出所用时间，得分，准确率
        Map<String, Object> map = baseMapper.getMap(examId);
        if (map != null && map.size() > 0) {
            //所用时间(秒)
            String sumExamMinute = map.get("sumExamMinute") == null ? "0分0秒" : map.get("sumExamMinute").toString();
            //得分(成绩)
            String totalScore = map.get("totalScore") == null ? "0" : map.get("totalScore").toString();
            //正确率
            String correctRate = map.get("correctRate") == null ? "0" : map.get("correctRate").toString();
            examResult.setSumExamMinute(sumExamMinute);
            examResult.setTotalScore(totalScore);
            examResult.setCorrectRate(correctRate);
        }
        //算出答题的正确数
        Map<String, Object> m = baseMapper.getM(examId);
        if (m != null && m.size() > 0) {
            //x为正确的题数
            Integer x = m.get("x") == null ? 0 : Double.valueOf(m.get("x").toString()).intValue();
            //y为做了的总题数
            Integer y = m.get("y") == null ? 0 : Double.valueOf(m.get("y").toString()).intValue();
            examResult.setTrueQuestionFrequency(x + "/" + y);
        }
        //查询出该学员在该科目还剩多少次考试次数
        Map<String, Object> scoreMap = baseMapper.getScoreMap(studentId, subjectId);
        if (scoreMap != null && scoreMap.size() > 0) {
            //已考试次数
            Integer examFrequency = scoreMap.get("examFrequency") == null ? 0 :
                    Double.valueOf(scoreMap.get("examFrequency").toString()).intValue();
            String remainFrequency = "不限";
            //科目默认有效次数次数，null或者0表示不限制
            Integer validFrequency = scoreMap.get("validFrequency") == null ? 0
                    : Double.valueOf(scoreMap.get("validFrequency").toString()).intValue();
            if (validFrequency != 0) {
                //如果科目有限制次数  剩余次数就用  科目有限制次数-学员在这科目上的已考试次数
                remainFrequency = String.valueOf(validFrequency - examFrequency);
                examResult.setRemainFrequency(remainFrequency);
            } else {
                examResult.setRemainFrequency(remainFrequency);
            }

        }
        return examResult;
    }

    /**
     * 获取考试记录
     *
     * @param params 分页用
     * @param page   默认第一页
     * @param size   默认一页10条数据
     * @return R
     * @author huolikang
     * @date 2018年10月30日
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params, Integer page, Integer size) {
        Query query = new Query(params);
        //获取考试记录
        List<Map<String, Object>> examList = this.baseMapper.queryList(query);
        return new PageUtils(examList, examList.size(), size, page);
    }

    /***
     * 查找学员未提交试卷id
     * @param studentId
     * @param subjectId
     * @return
     */
    @Override
    public Integer findUnommExamId(Long studentId, Integer subjectId) {

        return baseMapper.getUncommExamId(studentId, subjectId);
    }

    /***
     * 获取考试剩余试卷
     * @param paperMap
     * @return
     */
    @Override
    public Integer getRemainExamSecond(Map<String, Object> paperMap) {
        if (paperMap.size() < 0 && paperMap == null) {
            return 0;
        }
        //当前试卷考试剩余时间
        Integer remainExamSecond = paperMap.get("remainExamSecond") == null ? 0
                : Double.valueOf(paperMap.get("remainExamSecond").toString()).intValue();
        return remainExamSecond;

    }


}
